
GooglePlaceService = function(opts) {
    this.opts = opts;
    this.placeService = new google.maps.places.PlacesService(opts.map);
};

GooglePlaceService.prototype = {
    places: function(opts) {
        var handler = opts.handler;
        var location = opts.location;
        var radius = opts.radius || 300;
        var types = this.googlePlaceTypesForTypes(opts.types);
        console.log('looking for places of types', types);

        var request = {
            location: new google.maps.LatLng(location.lat, location.lng),
            radius: radius,
            types: types
        };
        this.placeService.search(request, $.proxy(this.placeSearchResponse, this, handler));
    },

    placeSearchResponse: function(handler, results, status, pagination) {
        if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
            handler([]);
            return;
        }

        if (status != google.maps.places.PlacesServiceStatus.OK) {
            console.log(handler, results, status);
            handler();
            return;
        }

        var places = $.map(results, $.proxy(function(r) {
            console.log('google response', r, r.formatted_address);
            return {
                name: r.name,
                type: this.placeTypesForGooglePlaceTypes(r.types),
                address: r.vicinity,
                lat: r.geometry.location.lat(),
                lng: r.geometry.location.lng()
            };
        }, this));
        handler(places);
    },

    googlePlaceTypesForTypes: function(types) {
        return $.map(types, $.proxy(function(t) {
            return this.googlePlaceTypes[t.name];
        }, this));
    },

    placeTypesForGooglePlaceTypes: function(types) {
        return $.map(types, $.proxy(function(t) {
            return PlaceType[this.placeTypes[t]];
        }, this));
    },

    googlePlaceTypes: {
        superMarket: 'grocery_or_supermarket',
        mall: 'shopping_mall',
        bar: 'bar',
        dentistOffice: 'dentist'
    },

    placeTypes: {
        grocery_or_supermarket: 'superMarket',
        shopping_mall: 'mall',
        bar: 'bar',
        dentist: 'dentistOffice'
    }
};
